﻿using System;
using System.Collections.Generic;

namespace XamlingCore.Infrastructure.Callbacks
{
    public class QueueCallback
    {
        private Queue<Action> queue = new Queue<Action>();

        private bool isRunning;

        private TimeSpan timeSpan;

        public QueueCallback(TimeSpan timeout)
        {
            timeSpan = timeout;
        }

        public void Add(Action callback)
        {
            queue.Enqueue(callback);

            if (!isRunning)
            {
                dequeue();
            }
        }

        void dequeue()
        {
            if (queue.Count > 0)
            {
                isRunning = true;
                var cb = queue.Dequeue();
                cb();
                TimeoutCallback.Callback(timeSpan, () =>
                {
                    dequeue();
                });

            }
            else
            {
                isRunning = false;
            }
        }
    }
}
